package com.umpay.privi.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.umpay.privi.common.ReqMessage;
import com.umpay.privi.common.ResMessage;
import com.umpay.privi.common.RetCode;
import com.umpay.privi.exception.BusinessException;
import com.umpay.privi.util.DateUtil;
import com.umpay.privi.util.PropertiesUtil;
import com.umpay.privi.util.StringUtil;

@Component
@Aspect
public class OperAccessInterceptorAspect
{
	private static final Logger log_ = LoggerFactory.getLogger(OperAccessInterceptorAspect.class);

	// 环绕配置通知
	@Around("execution(* com.umpay.privi.ejb..*(..)) ")
	public Object profile(ProceedingJoinPoint joinPoint) throws Throwable
	{
		log_.info("进入拦截器");
		long beginTime = System.currentTimeMillis();
		String methodName = joinPoint.getSignature().getName();
		Object[] paras = joinPoint.getArgs();

		ResMessage res = new ResMessage();
		if (paras.length != 1)
		{
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("请求参数个数错误");
			log_.info("错误返回:" + res);
			return res;
		}
		Object o = paras[0];
		if (o == null || !(o instanceof ReqMessage))
		{
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("请求参数类型错误");
			log_.info("错误返回:" + res);
			return res;
		}
		ReqMessage req = (ReqMessage) o;
		String name = Thread.currentThread().getName();
		Thread.currentThread().setName(name + "_" + req.getRpid());// 将rpid放入线程名称中打印，便于日志的统计与分析

		res.setRpid(req.getRpid());
		// 1、判断参数完整性
		if (StringUtil.isEmpty(req.getRpid()))
		{
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			res.setRetCode(RetCode.REQPARAM_ERR);
			res.setRetMsg("rpid为空");
			log_.info("错误返回:" + res);
			return res;
		}
		// ThreadValue.put("rpid", req.getRpid());

		if (StringUtil.isEmpty(req.getReqDate()))
		{
			req.setReqDate(DateUtil.date8());
			System.out.println("[" + methodName + ":reqDate为空,默认设置为当前日期:" + req.getReqDate());
			log_.info("[" + methodName + ":reqDate为空,默认设置为当前日期:" + req.getReqDate());

		}
		if (StringUtil.isEmpty(req.getReqTime()))
		{
			req.setReqTime(DateUtil.time6());
			System.out.println("[" + methodName + ":reqTime为空,默认设置为当前时间" + req.getReqTime());
			log_.info("[" + methodName + ":reqTime为空,默认设置为当前时间" + req.getReqTime());
		}

		// 2、去除请求参数中的空格
		Iterator<Map.Entry<String, Object>> it = req.getReqMap().entrySet().iterator();
		Map<String, Object> temp = new HashMap<String, Object>();
		while (it.hasNext())
		{
			Map.Entry<String, Object> entry = it.next();
			Object ojb = entry.getValue();
			if (null != ojb)
			{
				if (ojb instanceof String)
					temp.put(entry.getKey(), StringUtil.trim(entry.getValue()));
				temp.put(entry.getKey(), entry.getValue());
			}
		}
		req.putAll(temp);

		// 3、执行被拦截的方法
		try
		{
			res.setRpid(req.getRpid());
			res = (ResMessage) joinPoint.proceed();

			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
			// 设置默认返回码及返回信息
			if (StringUtil.isEmpty(res.getRetCode()))
				res.setRetCode(RetCode.UNKNOWN);
			if (StringUtil.isEmpty(res.getRetMsg()))
			{
				String retMsg = PropertiesUtil.getValue(res.getRetCode());
				if (StringUtil.isEmpty(retMsg))
				{
					retMsg = PropertiesUtil.getValue(RetCode.UNKNOWN);
				}
				res.setRetMsg(retMsg);
			}
		}
		catch (Exception e)
		{
			log_.error("执行方法" + joinPoint.getSignature().getName() + "发生异常", e);
			if (e instanceof BusinessException)
			{
				BusinessException ce = (BusinessException) e;
				res.setRetCode(ce.getCode());
				res.setRetMsg(ce.getMessage());
				res.put(ce.getInfomation());
			}
			else
			{
				// 系统忙请稍后再试
				String errCode = RetCode.UNKNOWN;
				String errMsg = PropertiesUtil.getValue(errCode);
				res.setRetCode(errCode);
				res.setRetMsg(errMsg);
			}
			long endTime = System.currentTimeMillis();
			long duration = endTime - beginTime;
			res.setTookTime(duration);
		}
		finally
		{
			// 如果返回报文中rpid为空，则填充rpid
			if (StringUtil.isEmpty(res.getRpid()))
			{
				res.setRpid(req.getRpid());
			}

		}
		return res;
	}

}
